<?php

namespace app\api\controller\store;

use app\api\controller\Base;
use app\common\service\store\GoodsCouponService;
use think\Request;

class GoodsCoupon extends Base
{
    /**
     * Author:Zhongyuan Lu
     * 查询商品优惠券
     * @return mixed|void
     */
    public function getGoodsCouponList()
    {
        $uid = $this->request->uid;
        $goodsId = $this->request->get('goods_id');
        if (is_int($goodsId) && $goodsId <= 0) {
            return $this->result([],400,'参数错误');
        }elseif (strpos($goodsId,',')) {
            $goodsId = explode(',',$goodsId);
        }elseif (is_array($goodsId)) {
            $goodsId = array_unique($goodsId);
            foreach ($goodsId as $v){
                if (!is_int($v) || $v <= 0) {
                    return $this->result([],400,'参数错误');
                }
            }
        }
        //获取商品对应的优惠券id
        $data = GoodsCouponService::getGoodsCouponId($goodsId);
        if ($data['code'] == 200) {
            //获取优惠券信息
            $data = GoodsCouponService::getGoodsCoupon(1,$data['data'],$uid);
        }
        return $this->res($data);
    }

    /**
     * Author:Zhongyuan Lu
     * 查询通用优惠券
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCouponList()
    {
        $data = GoodsCouponService::getGoodsCoupon(0);
        return $this->res($data);
    }

    /**
     * Author:Zhongyuan Lu
     * 领取商品优惠券
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function collectCoupon()
    {
        $uid = $this->request->uid;
        $couponId = $this->request->post('coupon_id',0,'int');
        $goodsId = $this->request->post('goods_id',0,'int');
        if (!is_int($couponId) || $couponId <= 0) {
            return $this->result([],400,'参数错误');
        }

        $data = GoodsCouponService::collectCoupon($uid,$couponId,$goodsId);
        return $this->res($data);
    }


    public function couponById(Request $request)
    {
        $couponId = $request->get('coupon_id');
        $coupon = \app\admin\model\store\GoodsCoupon::find($couponId);
        $coupon && $coupon = $coupon->toArray();
        $data = ['code'=>200,'messageg'=>'成功','data'=>$coupon];
        return json($data);
    }
}